package com.qfchen.downloadhelper;

import java.io.IOException;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class OkHttpClientUtils {

	public static String getStringFromUrl(String url) {
		String string = null;
		// 创建OkHttp的对象
		OkHttpClient client = new OkHttpClient();
		// 创建请求,将地址写入
		Request request = new Request.Builder().url(url).build();
		try {
			Response response = client.newCall(request).execute();
			// 判断是否访问成功,取出数据写入本地
			if (response.isSuccessful()) {
				// 返回数据
				string = response.body().string();

				// // 保存图片
				// byte[] bs = response.body().bytes();// 将服务器返回数据写到byte数组
				// // 将数组写到图片
				// FileOutputStream fos = new FileOutputStream(new
				// File("b.jpg"));
				// fos.write(bs);
				// fos.flush();
				// if (fos != null) {
				// fos.close();
				// }
			}
		} catch (IOException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		return string;
	}

	public static byte[] getByteFromUrl(String url) throws IOException {

		OkHttpClient client = new OkHttpClient();
		Request request = new Request.Builder().url(url).build();
		Response response = null;
		try {
			response = client.newCall(request).execute();
			if (response.isSuccessful()) {
				byte[] bs = response.body().bytes();
				
				return bs;
			}
			
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		return null;
	}
	
	public static Bitmap getBitmapFromUrl(String url){
		
		Bitmap bitmap = null;
		OkHttpClient client = new OkHttpClient();
		Request request = new Request.Builder().url(url).build();
		Response response = null;
		try {
			response = client.newCall(request).execute();
			if (response.isSuccessful()) {
				byte[] bs = response.body().bytes();
				bitmap = BitmapFactory.decodeByteArray(bs, 0, bs.length);
				return bitmap;
			}
			
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		return null;
	}
	
}
